package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;


    // TODO:事务，新增菜品时还要同时对口味表进行操作
    @Override
    @Transactional
    public void insert(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        // 拿到执行insert语句后生成的主键值，即dish表中的id，后续插入口味表时要用
        Long dish_id = dish.getId();

        // 还要操作口味表
        List<DishFlavor> flavors = dishDTO.getFlavors();

        // 判断口味表是否为空，如果不为空则向dish_flavor插入数据
        if (flavors != null && flavors.size() > 0) {
            // 每次都给dish_id进行赋值
            flavors.stream().forEach(dishFlavor -> {
                dishFlavor.setDishId(dish_id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    // TODO:分页查询对多表进行操作
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        PageHelper.startPage(page, pageSize);

        List<DishVO> dishVO = dishMapper.pageQuery(dishPageQueryDTO);
        Page<DishVO> p = (Page<DishVO>) dishVO;

        PageResult pageResult = new PageResult(p.getTotal(), p.getResult());
        return pageResult;
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(Long[] ids) {
        // 起售中的菜品不能删除
        for (int i = 0; i < ids.length; i++) {
            DishVO dishVO = dishMapper.getById(String.valueOf(ids[i]));
            if (dishVO.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 判断是否和套餐表有关联
        List<Long> list = setMealDishMapper.getMealIdByDishId(ids);
        log.info("获取到的mealid为{}", list);
        if (list != null && list.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        // 删除时还要把所关联的口味也删除
        dishMapper.deleteDish(ids);
        dishFlavorMapper.deleteDishFlavor(ids);
    }

    /**
     * 根据ID查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(String id) {
        DishVO dishVO = dishMapper.getById(id);

        // 调用DishFlavorMapper中的方法来将口味数据封装到flavors字段
        List<DishFlavor> dishFlavors = dishFlavorMapper.getById(id);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public List<Dish> list(String categoryId) {
        Dish dish = Dish.builder()
                .categoryId(Long.valueOf(categoryId))
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList = dishMapper.list(dish);
        return dishList;
    }

    /**
     * 启用，禁用员工
     *
     * @param status
     * @param id
     */
    @Override
    public void dishStatus(String status, String id) {
        dishMapper.dishStatus(status, id);
    }

    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //修改菜品
        dishMapper.update(dish);

        // TODO:修改口味相关逻辑
        //修改菜品口味
        //先删除原先的
        Long dishId = dishDTO.getId();
        Long[] dishIdArr = {dishId};
        dishFlavorMapper.deleteDishFlavor(dishIdArr);

        //再插入修改后的
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 插入给哪个id？要进行设置
        if (flavors != null && flavors.size() > 0) {
            // 每次都给dish_id进行赋值
            flavors.stream().forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getById(String.valueOf(d.getId()));

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
